package models

import (
	"database/sql"
	"github.com/gogf/gf/os/gfile"
	"github.com/sirupsen/logrus"
	"gopkg.in/ini.v1"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"path"
	"quantization_trading/src/util"
)

// 在其它model的实体类中可直接调用
var db *gorm.DB
var ModelLog *logrus.Logger

func InitDB(conf *ini.File) *sql.DB {
	var err error

	// 数据库的类型
	dbType := conf.Section("server").Key("db_type").String()

	// Mysql配置信息
	mysqlName := conf.Section("mysql").Key("db_name").String()
	mysqlUser := conf.Section("mysql").Key("db_user").String()
	mysqlPwd := conf.Section("mysql").Key("db_pwd").String()
	mysqlHost := conf.Section("mysql").Key("db_host").String()
	mysqlPort := conf.Section("mysql").Key("db_port").String()
	mysqlCharset := conf.Section("mysql").Key("db_charset").String()

	// sqlite3配置信息
	sqliteName := conf.Section("sqlite3").Key("db_name").String()

	var dataSource string
	switch dbType {
	case "mysql":
		dataSource = mysqlUser + ":" + mysqlPwd + "@tcp(" + mysqlHost + ":" +
			mysqlPort + ")/" + mysqlName + "?charset=" + mysqlCharset

		//db, err = gorm.Open(dbType, dataSource)
		db, err = gorm.Open(mysql.Open(dataSource), &gorm.Config{
			SkipDefaultTransaction: true, // 关闭写入操作默认启用事务
			DisableAutomaticPing:   true, // 关闭自动 Ping 数据库
			Logger:logger.Default.LogMode(logger.Info),
		})
	case "sqlite3":
		dataSource = "database" + string(os.PathSeparator) + sqliteName
		if !gfile.Exists(dataSource) {
			os.MkdirAll(path.Dir(dataSource), os.ModePerm)
			os.Create(dataSource)
		}
		//db, err = gorm.Open(dbType, dataSource)
		db, err = gorm.Open(sqlite.Open(dataSource), &gorm.Config{
			//SkipDefaultTransaction: true, // 关闭写入操作默认启用事务
			//DisableAutomaticPing:   true, // 关闭自动 Ping 数据库
			Logger:logger.Default.LogMode(logger.Info),
		})
	}
	db.AutoMigrate(&Account{},&AccountAsset{},&Asset{},&Order{},&Position{},&Price{},&Strategy{},&StrategyInfo{})

	// 获取通用数据库对象 sql.DB ，然后使用其提供的功能
	sqlDB, err := db.DB()
	if err != nil {
		log.Fatal(util.CONN_DATABASE_ERROR, err)
		sqlDB.Close()
	}
	// 设置连接池，空闲连接
	sqlDB.SetMaxIdleConns(50)
	// 打开链接
	sqlDB.SetMaxOpenConns(100)
	ModelLog = util.ModelLogger()


	return sqlDB
}

